<template>
  <div style="border: 1px solid #ccc">
    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
    <Editor
      style="height: 400px; overflow-y: hidden"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="handleChange"
      @onDestroyed="handleDestroyed"
      @onFocus="handleFocus"
      @onBlur="handleBlur"
      @customAlert="customAlert"
      @customPaste="customPaste"
    />
  </div>
</template>
<script>
const EVENTS = {
  UPDATE_VALUE: 'update:modelValue'
}
</script>
<script setup>
import { shallowRef, ref, onBeforeUnmount, watch } from 'vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { i18nChangeLanguage } from '@wangeditor/editor'
import { debounce } from 'lodash'

// 设置默认语言
i18nChangeLanguage(navigator.language)

// 表单html值-双向绑定配置
const valueHtml = ref('')

const emit = defineEmits(Object.values(EVENTS))
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
})
const emitChange = debounce(() => {
  emit(EVENTS.UPDATE_VALUE, valueHtml.value)
}, 500)

watch(
  () => props.modelValue,
  (value) => {
    valueHtml.value = value
  },
  {
    immediate: true
  }
)

// wangEditor基本配置
const mode = ref('default')
const editorRef = shallowRef()

const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }

// life-cycle 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

// 事件处理
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
const handleChange = () => {
  emitChange()
}

const handleDestroyed = (editor) => {
  // console.log('destroyed', editor)
}
const handleFocus = (editor) => {
  // console.log('focus', editor)
}
const handleBlur = (editor) => {
  // console.log('blur', editor)
}
const customAlert = (info, type) => {
  // alert(`【自定义提示】${type} - ${info}`)
}
const customPaste = (editor, event, callback) => {
  // console.log('ClipboardEvent 粘贴事件对象', event)
  // const html = event.clipboardData.getData('text/html') // 获取粘贴的 html
  // const text = event.clipboardData.getData('text/plain') // 获取粘贴的纯文本
  // const rtf = event.clipboardData.getData('text/rtf') // 获取 rtf 数据（如从 word wsp 复制粘贴）
  // 自定义插入内容
  // editor.insertText('xxx')
  // 返回 false ，阻止默认粘贴行为
  // event.preventDefault()
  // callback(false) // 返回值（注意，vue 事件的返回值，不能用 return）
  // 返回 true ，继续默认的粘贴行为
  // callback(true)
}
</script>
